package cn.fenqing168.nio;

import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.List;

/**
 * 使用Socket 做一个接受客户端请求并返回的功能
 * 主要使用Buffer的分散聚合
 * @author fenqing
 */
public class ScatteringAndGatheringDemo {

    public static void main(String[] args) {
        //创建一个ServerSocketChannel
        try(ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()){
            //创建一个地址
            InetSocketAddress inetSocketAddress = new InetSocketAddress(7700);
            //绑定地址
            serverSocketChannel.socket().bind(inetSocketAddress);
            //循环开始监听连接
            while (true){
                SocketChannel channel = serverSocketChannel.accept();
                //创建一个Buffer数组
                ByteBuffer[] buffers = {
                        ByteBuffer.allocate(10),
                        ByteBuffer.allocate(20)
                };
                List<ByteBuffer> byteBuffers = Arrays.asList(buffers);
                //开始读取数据并返回
                while (channel.read(buffers) != -1){
                    //输出每个buffer读到的数据
                    byteBuffers.forEach(buf -> System.out.println("buffer状态， position:" + buf.position() + ",limit:" + buf.limit()));
                    //反转每个buffer
                    byteBuffers.forEach(Buffer::flip);
                    //将buffer写出
                    channel.write(buffers);
                    //清空每个buffer
                    byteBuffers.forEach(Buffer::clear);
                }
                channel.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
